package com.example.apollotogit.service.imp;

import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigService;
import com.example.apollotogit.service.HandleService;
import com.example.apollotogit.utils.CMDUtils;
import com.example.apollotogit.utils.GetJsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.activation.MimetypesFileTypeMap;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
public class HandleServiceImpl implements HandleService {

    @Override
    public synchronized void getPrintInfo(Map<String, Object> map) throws Exception {
        System.out.println("now at getPrintInfo()");
        HandleServiceImpl handleServiceimp = new HandleServiceImpl();
        Map<String, String> resMap = handleServiceimp.checkParams(map);
        System.out.println("resMap handle completed");
        if (!resMap.isEmpty() && resMap.containsKey("isContinue") && resMap.containsKey("updateEnvironment")) {
            System.out.println("resMap.containsKey = "+resMap.containsKey("isContinue")+"-----resMap.containsKey = "+resMap.containsKey("updateEnvironment"));
            Map jsonCon = GetJsonUtil.getAddress();
            System.out.println("local jsonMap = " + jsonCon);
            String updateEnvironment = "";
            if (jsonCon.containsKey("updateEnvironment"))
                updateEnvironment = (String)jsonCon.get("updateEnvironment");
            if ((resMap.get("isContinue")).equals("true") && (resMap.get("updateEnvironment")).contains(updateEnvironment)) {
                System.out.println("isContinue == true && updateEnvironment is equally");
                if (resMap.containsKey("address") && resMap.get("address") != null) {
                    System.out.println("address element is exist");
                    Map<String, String> cmdMap = handleServiceimp.runCmd(resMap.get("address"), resMap.get("commitPerson"), updateEnvironment);
                    System.out.println("cmd run completed");
                    if (!(cmdMap.get("resCmd")).equals("") || !(cmdMap.get("svnResStr")).equals("")) {
                        System.out.println("cmd run result is correct");
                        String bigAntPrint = handleServiceimp.constrResult(cmdMap, resMap);
                        handleServiceimp.sendBigAnt("git更新通知", bigAntPrint);
                        System.out.println("bigant send completed");
                        log.info("git更新结果------------------\n" + bigAntPrint);
                    } else {
                        log.info("不存在此路径"+ resMap.get("address"));
                    }
                }
            } else if ((resMap.get("isContinue")).equals("false")) {
                log.info("state!=merged 不需要处理");
            } else {
                log.info("updateEnvironment=" + resMap.get("updateEnvironment"));
            }
        }
        System.gc();
    }

    /**
     * 获取完整的大蚂蚁发送消息
     *
     * @param cmdMap cmd运行结果
     * @param resMap 相关信息map
     * @return 输出消息
     */
    private String constrResult(Map<String, String> cmdMap, Map<String, String> resMap) {
        String printStr = "";
        String log = "";
        if ((cmdMap.get("svnResStr")).equals("") && !(cmdMap.get("resCmd")).equals("")) {
//            if ((cmdMap.get("resCmd")).indexOf("Fast-forward") != -1) {
            if ((cmdMap.get("resCmd")).indexOf("Already") == -1 && (cmdMap.get("resCmd")).indexOf("Please") == -1) {
                resMap.put("updateRes", "更新成功");
            } else {
                resMap.put("updateRes", "更新失败");
            }
            log = cmdMap.get("resCmd");
        } else {
//            if ((cmdMap.get("resCmd")).indexOf("Fast-forward") != -1 && (cmdMap.get("svnResStr")).indexOf("success") != -1) {
            if ((cmdMap.get("resCmd")).indexOf("Already") == -1 && (cmdMap.get("resCmd")).indexOf("Please") == -1 && (cmdMap.get("svnResStr")).indexOf("success") != -1) {
                resMap.put("updateRes", "更新成功");
            } else {
                resMap.put("updateRes", "更新失败");
            }
            log = cmdMap.get("resCmd") + "\n---------SVN---------\n" + cmdMap.get("svnResStr");
        }
        resMap.put("updateLog", log);
        SimpleDateFormat sdf = new SimpleDateFormat();// 格式化时间
        sdf.applyPattern("yyyy-MM-dd HH:mm:ss a");// a为am/pm的标记
        sdf.setTimeZone(TimeZone.getTimeZone("Etc/GMT-8"));
        Date date = new Date();// 获取当前时间
        resMap.put("updateTime", sdf.format(date) + "");

        printStr = "代码仓库名称：" + resMap.get("storeName")
                + "\n提交人：" + resMap.get("commitPerson")
                + "\n审核人：" + resMap.get("assigneeName")
                + "\n提交备注:" + resMap.get("commitMarks")
                + "\n更新环境：" + resMap.get("updateEnvironment")
                + "\n更新结果：" + resMap.get("updateRes")
                + "\n更新日志:" + resMap.get("updateLog")
                + "\n更新时间：" + resMap.get("updateTime");
        return printStr;
    }

    /**
     * 检查特定参数是否符合要求
     *
     * @param map 传参
     * @return resMap 结果集
     */
    public Map<String, String> checkParams(Map<String, Object> map) throws IOException {
        System.out.println("now at chechParams");
        Map<String, String> resMap = new HashMap<>();//此处记得初始化时一定要分配内存否则可能会产生NullPointerException
        Map<String, String> project = new HashMap<>();
        Map<String, Object> object_attributes = new HashMap<>();
        Map<String, String> user = new HashMap<>();
        Map<String, String> target = new HashMap<>();
        Map<String, String> object_attributes_source = new HashMap<>();
        List<Map<String, String>> assignees = new ArrayList<>();
        Map<String, Object> last_commit = new HashMap<>();
        Map<String, String> author = new HashMap<>();
        String namespace = "";
        String state = "";
        String compareAddress = "";
        String source_namespace = "";
        String commitPerson = "";
        String assigneeName = "";
        String message = "";
        String updateEnvironment = "";
        String cmitName = "";

        if (map.containsKey("project"))
            project = (Map<String, String>) map.get("project");
        if (map.containsKey("object_attributes"))
            object_attributes = (Map<String, Object>) map.get("object_attributes");
        if (map.containsKey("user"))
            user = (Map<String, String>) map.get("user");
        if (map.containsKey("assignees"))
            assignees = (List<Map<String, String>>) map.get("assignees");

        if (project != null && project.containsKey("path_with_namespace"))
            namespace = project.get("path_with_namespace");
        //合并状态
        if (object_attributes != null && object_attributes.containsKey("state"))
            state = (String) object_attributes.get("state");
        //目标分支，更新环境
        if (object_attributes != null && object_attributes.containsKey("target_branch"))
            updateEnvironment = (String) object_attributes.get("target_branch");

        //仓库名1
        if (object_attributes != null && object_attributes.containsKey("source")) {
            object_attributes_source = (Map<String, String>) object_attributes.get("source");
            if (object_attributes_source != null && object_attributes_source.containsKey("namespace"))
                source_namespace = object_attributes_source.get("namespace");
            //比对路径
            if (object_attributes_source != null && object_attributes_source.containsKey("path_with_namespace"))
                compareAddress = object_attributes_source.get("path_with_namespace");
        }
        //仓库名2
        if (project != null && project.containsKey("path_with_namespace"))
            namespace = project.get("path_with_namespace");
        //提交人
        if (user != null && user.containsKey("name"))
            commitPerson = user.get("name");
        //审核人
        if (assignees != null && assignees.size() >= 1) {
            if (!assignees.get(0).isEmpty() && assignees.get(0).containsKey("name")) {
                assigneeName = assignees.get(0).get("name");
            }
        }
        //提交备注
        if (object_attributes != null && object_attributes.containsKey("last_commit")) {
            last_commit = (Map<String, Object>) object_attributes.get("last_commit");
            if (last_commit != null && last_commit.containsKey("message"))
                message = (String) last_commit.get("message");
            if (last_commit != null && last_commit.containsKey("author")) {
                author = (Map<String, String>) last_commit.get("author");
                if (author != null && author.containsKey("name"))
                    cmitName = author.get("name");
            }
        }
        System.out.println("state=" + state);
        //判断是否为merged状态
        if (state.equalsIgnoreCase("merged")) {
            //判断namespace是否符合要求,并获取邮件相关信息
            HandleServiceImpl handleService = new HandleServiceImpl();
            String targetBranch = handleService.getTargetBranch(compareAddress);
            resMap.put("address", targetBranch);
            resMap.put("storeName", source_namespace + " " + namespace);
            resMap.put("commitPerson", cmitName);
            resMap.put("assigneeName", commitPerson);
            resMap.put("commitMarks", message);
            resMap.put("updateEnvironment", updateEnvironment);
            resMap.put("isContinue", "true");
            return resMap;
        }
        resMap.put("isContinue", "false");
        return resMap;
    }

    /**
     * cmd运行
     *
     * @param address 地址
     * @return resCmd 返回值
     */
    public Map<String, String> runCmd(String address, String name, String environment) throws Exception {
        String resCmd = "";
        String svnResStr = "";
        String pre = "";
        String ref = "";
        HashMap<String, String> cmdMap = new HashMap<>();
        CMDUtils cmdUtils = new CMDUtils();
        File file = new File(address);
        if (file.exists()) {
            resCmd = CMDUtils.execCmd("/data/svnrepo/json/gitpull.sh ", file);
            if (environment.equals("master")) {
//                String fileStr = CMDUtils.execCmd("ls -al", file);
//                fileStr = fileStr.replace("\n", " ").trim();
//                fileStr = fileStr.replace(".git ", "");
//                log.info("add=" + fileStr);
//                String svnAdd = CMDUtils.execCmd("svn add " + fileStr + " --force", file);
//                log.info(svnAdd);
                log.info("/data/svnrepo/json/svncommit.sh " + address + " " + name);
                String svnCommit = CMDUtils.execCmd("/data/svnrepo/json/svncommit.sh " + address + " " + name, file);
//                String[] split = svnCommit.split("--trust-server-cert");
//                svnCommit = split[1];
//                log.info(svnCommit);
                svnResStr = svnCommit;
            }
        }
        cmdMap.put("resCmd", resCmd);
        cmdMap.put("svnResStr", svnResStr);
        return cmdMap;
    }


    /**
     * 根据目标分支获取具体的本地路径相关信息
     *
     * @param aim 目标分支
     * @return 本地路径相关信息
     */
    public String getTargetBranch(String aim) throws IOException {
        String branchInfo = "";
        Map jsonCon = GetJsonUtil.getAddress();
        String namespace = "";
        if (jsonCon.containsKey("namespace")) {
            namespace = (String) jsonCon.get("namespace");
        }
        // 得到当前app.id中的配置
        log.info(aim + "+" + namespace);
        Config config = ConfigService.getConfig(namespace); //config instance is singleton for each namespace and is never null
        branchInfo = config.getProperty(aim, null);
        System.out.println("拉取路径：" + branchInfo);
        return branchInfo;
    }

    /**
     * 发送大蚂蚁消息
     *
     * @param title   内容标题
     * @param content 内容
     */
    public void sendBigAnt(String title, String content) throws IOException {
        //获取群秘钥
        String recver = "";
        Map address = GetJsonUtil.getAddress();
        if (address.containsKey("recver")) {
            recver = (String) address.get("recver");
        }
        send(recver, title, content);
    }

    /**
     * 发送bigant封装
     *
     * @param recver  编号
     * @param title   标题
     * @param content 内容
     */
    public static void send(String recver, String title, String content) {
        String url1 = "http://139.196.185.172:9898/dejax/send_group";
        String fileName = null;
        Map<String, String> textMap = new HashMap<String, String>();

        //可以设置多个input的key，value
        textMap.put("recver", recver);
        textMap.put("subject", title);
        textMap.put("content", content);

        //设置file的name，路径
        Map<String, String> fileMap = new HashMap<>();
        fileMap.put("upfile", fileName);
        String contentType = "";//image/png
        formUpload(url1, textMap, fileMap, contentType);
    }

    /**
     * 上传图片
     *
     * @param urlStr
     * @param textMap
     * @param fileMap
     * @param contentType 没有传入文件类型默认采用application/octet-stream
     *                    contentType非空采用filename匹配默认的图片类型
     * @return 返回response数据
     */
    @SuppressWarnings("rawtypes")
    public static String formUpload(String urlStr, Map<String, String> textMap,
                                    Map<String, String> fileMap, String contentType) {
        String res = "";
        HttpURLConnection conn = null;
        // boundary就是request头和上传文件内容的分隔符
        String BOUNDARY = "---------------------------123821742118716";
        try {
            //代理
//            Proxy proxy = new Proxy(java.net.Proxy.Type.HTTP,
//                    new InetSocketAddress("127.0.0.1", 8888));
            URL url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
            OutputStream out = new DataOutputStream(conn.getOutputStream());
            // text
            if (textMap != null) {
                StringBuffer strBuf = new StringBuffer();
                Iterator iter = textMap.entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry entry = (Map.Entry) iter.next();
                    String inputName = (String) entry.getKey();
                    String inputValue = (String) entry.getValue();
                    if (inputValue == null) {
                        continue;
                    }
                    strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
                    strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n");
                    strBuf.append(inputValue);
                }
                out.write(strBuf.toString().getBytes());
            }
            // file
            if (fileMap != null) {
                Iterator iter = fileMap.entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry entry = (Map.Entry) iter.next();
                    String inputName = (String) entry.getKey();
                    String inputValue = (String) entry.getValue();
                    if (inputValue == null) {
                        continue;
                    }
                    File file = new File(inputValue);
                    String filename = file.getName();

                    //没有传入文件类型，同时根据文件获取不到类型，默认采用application/octet-stream
                    contentType = new MimetypesFileTypeMap().getContentType(file);
                    //contentType非空采用filename匹配默认的图片类型
                    if (!"".equals(contentType)) {
                        if (filename.endsWith(".png")) {
                            contentType = "image/png";
                        } else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".jpe")) {
                            contentType = "image/jpeg";
                        } else if (filename.endsWith(".gif")) {
                            contentType = "image/gif";
                        } else if (filename.endsWith(".ico")) {
                            contentType = "image/image/x-icon";
                        }
                    }
                    if (contentType == null || "".equals(contentType)) {
                        contentType = "application/octet-stream";
                    }
                    StringBuffer strBuf = new StringBuffer();
                    strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
                    strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + filename + "\"\r\n");
                    strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
                    out.write(strBuf.toString().getBytes());
                    DataInputStream in = new DataInputStream(new FileInputStream(file));
                    int bytes = 0;
                    byte[] bufferOut = new byte[1024];
                    while ((bytes = in.read(bufferOut)) != -1) {
                        out.write(bufferOut, 0, bytes);
                    }
                    in.close();
                }
            }
            byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
            out.write(endData);
            out.flush();
            out.close();
            // 读取返回数据
            StringBuffer strBuf = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                strBuf.append(line).append("\n");
            }
            res = strBuf.toString();
            reader.close();
            reader = null;
        } catch (Exception e) {
            System.out.println("发送POST请求出错。" + urlStr);
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
        }
        return res;
    }
}
